<?php


namespace App\Exports;


use App\Models\PartCompany;
use App\Models\ProjectClassify;
use App\Services\BaseService;
use App\Services\CommonService;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

/**
 * Class BookTitleExport29
 * @package App\Exports
 * 29号案卷目录导出格式
 */
class BookTitleExportLY implements  FromCollection, WithTitle, WithColumnWidths, WithStyles,  WithCustomStartCell
{
    use Exportable;

    protected  $totalRow; //总行数
    protected  $partCompanyId; //参见单位
    protected  $partCompanyName; //参见单位名字
    protected  $projectClassifyId; //项目分类
    protected  $projectClassifyName; //项目分类名称
    protected  $bookTitleIds;

    public function __construct($bookTitleIds)
    {
        $this->partCompanyId       = request()->input('part_company_id', 0);
        $this->partCompanyName     = PartCompany::query()->where('id', $this->partCompanyId)->value('title');
        $this->projectClassifyId   = request()->input('project_classify_id', 0);
        $this->projectClassifyName = ProjectClassify::query()->where('id', $this->projectClassifyId)->value('title');
        $this->bookTitleIds        = $bookTitleIds;
    }

    /**
     * 获取数据集合
     */
    public function collection()
    {
        $bookTitleInstance = (new BaseService())->getBookTitleInstance($this->partCompanyId, $this->projectClassifyId);
        $bookTitleIds = $this->bookTitleIds;
        $list = $bookTitleInstance
            ->when($bookTitleIds, function ($query) use ($bookTitleIds) {
                return $query->whereIn('id', $bookTitleIds);
            })
            ->where('part_company_id', $this->partCompanyId)
            ->where('project_classify_id', $this->projectClassifyId)
            ->select('id','archives_no','title','word_material','blueprint','page_num','store_period','secret_level','start_date','end_date','volume','remark')
            ->orderBy('serial_no')
            ->get();

        if ($list->isEmpty()) return collect([]);

        $list = $list->toArray();

        $r_list = [];
        foreach ($list as $key => $val) {
            $arr['number']         = $key + 1;              //序号
            $arr['archives_no']    = str_replace('•', '·',$val['archives_no'])   ;   //档案号
            $arr['title']          = htmlspecialchars_decode($val['title']); //标题
            $arr['word_material']  = $val['word_material']; //文字
            $arr['blueprint']      = $val['blueprint'] ?: '/'; //蓝图
            $arr['total_page']     = $val['page_num']; //总张数
            $arr['part_company']   = $this->partCompanyName; //形成单位
            $arr['start_end_date'] = format_date($val['start_date'], $val['end_date']); //起止日期
            $arr['store_period']   = $val['store_period'];  //保管期限
            $arr['secret_level']   = ''; //密级
            $arr['volume']         = ''; //册数
            $arr['box_size']       = ''; //盒子尺寸
            $arr['store_place']    = ''; //存放位置
            $arr['remark']         = ''; //备注
            $arr['data_count']     = CommonService::getBookCatalogInstance($this->partCompanyId, $this->projectClassifyId)->where('book_title_id', $val['id'])->count() ?: 0;
            $r_list[]              = $arr;
        }
        $this->totalRow = count($r_list) + 5;

        return collect($r_list);
    }

    /**
     * sheet名称
     * @return string
     */
    public function title(): string
    {
        return $this->projectClassifyName;
    }

    /**
     * 设置列宽
     * @return array
     */
    public function columnWidths(): array
    {
        return [
            'A' => 10, 'B' => 20, 'C' => 60, 'D' => 6, 'E' => 10, 'F' => 9, 'G' => 12, 'H' => 20, 'I' => 12, 'J' => 6, 'K' => 6, 'L' => 6, 'M' => 6, 'N' => 6,  'O' => 6
        ];
    }

    /**
     * 从哪个单元格开始渲染数据，数据集合如 $list
     * @return string
     */
    public function startCell(): string
    {
        return 'A6';
    }

    /**
     * 样式设置
     * @param Worksheet $sheet
     * @throws PhpSpreadsheetException
     */
    public function styles(Worksheet $sheet)
    {
        $sheet->mergeCells('A1:O1');
        $sheet->setCellValue('A1', '科  技  档  案  案  卷  目  录');

        $sheet->mergeCells('A2:C2');
        $sheet->setCellValue('A2', '建设项目（简称）：');

        $sheet->mergeCells('D2:G2');
        $sheet->setCellValue('D2', '专业：');

        $sheet->mergeCells('H2:N2');
        $sheet->setCellValue('H2', '里程段：');

        $sheet->mergeCells('A3:A5'); //序号
        $sheet->mergeCells('B3:B5'); //档案号
        $sheet->mergeCells('C3:C5'); //案卷题名
        $sheet->mergeCells('D3:F3'); //案卷页数
        $sheet->mergeCells('D4:D5'); //文字
        $sheet->mergeCells('E4:E5'); //蓝图
        $sheet->mergeCells('F4:F5'); //总张数
        $sheet->mergeCells('G3:G5'); //形成单位
        $sheet->mergeCells('H3:H5'); //形成时间
        $sheet->mergeCells('I3:I5'); //保管期限
        $sheet->mergeCells('J3:J5'); //密级
        $sheet->mergeCells('K3:K5'); //册数
        $sheet->mergeCells('L3:L5'); //盒子尺寸
        $sheet->mergeCells('M3:M5'); //存放位置
        $sheet->mergeCells('N3:N5'); //备注
        $sheet->mergeCells('O3:O5'); //卷内数量
        /**
         * 属性名设置
         */
        $sheet->setCellValue('A3', '序号');
        $sheet->setCellValue('B3', '档案号');
        $sheet->setCellValue('C3', '案卷名称');
        $sheet->setCellValue('D3', '张数');
        $sheet->setCellValue('D4', '文字');
        $sheet->setCellValue('E4', '蓝图');
        $sheet->setCellValue('F4', '总张数');
        $sheet->setCellValue('G3', '形成单位');
        $sheet->setCellValue('H3', '形成时间');
        $sheet->setCellValue('I3', '保管期限');
        $sheet->setCellValue('J3', '密级');
        $sheet->setCellValue('K3', '册数');
        $sheet->setCellValue('L3', '盒子尺寸');
        $sheet->setCellValue('M3', '存放位置');
        $sheet->setCellValue('N3', '备注');
        $sheet->setCellValue('O3', '卷内数量');
        /**
         * 顶部案卷目录样式设置
         */
        $sheet->getStyle('A1')->getFont()->setSize(24); //大小
        $sheet->getStyle('A1')->applyFromArray([
            'font' => [
                'size' => 24,
                'name' => '宋体',
                'bold' => true,
            ],
            'alignment' => [
                'vertical' => 'left',
            ],
        ]);
        $sheet->getStyle('A1:O' . $this->totalRow)->getAlignment()->setVertical('center');//垂直居中
        $sheet->getStyle('A1:O' . $this->totalRow)->getAlignment()->setHorizontal('center');//水平居中
        $sheet->getStyle('A1:O' . $this->totalRow)->getAlignment()->setWrapText(true); //自动换行
        $sheet->getStyle('A2:O2')->applyFromArray([
            'font' => [
                'size' => 12,
                'name' => '仿宋_GB2312',
            ],
            'alignment' => [
                'vertical'   => 'center',
                'horizontal' => 'left', //水平靠左
            ],
        ]);
        $sheet->getStyle('A3:O3')->applyFromArray([
            'font' => [
                'size' => 12,
                'name' => '仿宋_GB2312',
            ],
        ]);
        $sheet->getStyle('D4:O4')->applyFromArray([
            'font' => [
                'size' => 12,
                'name' => '仿宋_GB2312',
            ],
        ]);
        $sheet->getStyle('A6:O'.$this->totalRow)->applyFromArray([
            'font' => [
                'size' => 11,
                'name' => '仿宋_GB2312',
            ],
        ]);
        $sheet->getStyle('C6:C'.$this->totalRow)->applyFromArray([
            'alignment' => [
                'horizontal' => 'left', //水平靠左
            ],
        ]);
        for ($row = 1; $row <= $this->totalRow; $row++) { //设置行高
            if ($row == 3 || $row == 4 || $row == 5) {
                $sheet->getRowDimension($row)->setRowHeight(15);
            } else {
                $sheet->getRowDimension($row)->setRowHeight(42);
            }
        }
        /**
         * 设置边框
         */
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' =>  Border::BORDER_THIN //细边框
                ]
            ]
        ];
        $sheet->getStyle('A3:O'.$this->totalRow)->applyFromArray($styleArray);
    }

}
